import { Component, OnInit } from '@angular/core';
import { element } from 'protractor';
// 引入服务
import { StorageService } from '../../services/storage.service';

// 不推荐
// let storage = new StorageService();
// console.log(storage)

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {

  public keyword:string= ''
  public historyList:string[]=[]
  // public todoList:any[]=[];

  todoList = [
  {
    title:'xxx',
    status:0
  },
  {
    title:'xxx',
    status:0
  }
]

  constructor(public stroage:StorageService) {
     
   }

  ngOnInit(): void {
    console.log('页面刷新会触发这个生命周期');
    let searchlist:any= this.stroage.get('searchList');
    console.log(searchlist)
    if(searchlist) {
      this.historyList=searchlist;
    }
  }
  doSearch() {
    if (this.historyList.indexOf(this.keyword)==-1) {
        this.historyList.push(this.keyword);
        //缓存
        this.stroage.set('searchList',this.historyList)
    }
    this.keyword=''
  }
  deleteHistory(key:any) {
   this.historyList.splice(key,1)
  }
  doAdd(event:any) {
    if(event.keyCode==13) {
      
      if(!this.todoListHasKeyword(this.todoList,this.keyword)) {
        this.todoList.push({
          title:this.keyword,
          status:0 //0代表待办事项，1表示已完成事项
        });
        this.keyword='';
      }else {
        alert('数据已经存在');
        this.keyword='';
      }
      }
  }
  deleteData(key:any) {
    this.todoList.splice(key,1)
  }
  //如果数组存在keyword返回true,否则返回false
  todoListHasKeyword(todoList:any,keyword:any) {

    if(!keyword) return false;

    for(var i=0;i<todoList.length;i++) {
      if(todoList[i].title==keyword) {
        return true;
      }
    }
    return false;
  
  }

}
